package com.association.main.frontcontroller;

import com.association.main.common.CustomException;
import com.association.main.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/front")
public class FCommonController {
    @Value("${docPath}")
    private String docPath;
    @PostMapping("/uploadWordFile")
    public R<String> upload(MultipartFile file){
// 判断文件是否为空
        if (file.isEmpty()) {
            throw new CustomException("上传的文件为空");
        }
// 判断文件类型是否为word
        if (!file.getContentType().equals("application/msword") && !file.getContentType().equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
            throw new CustomException("只能上传Word文件");
        }
//获取文件名并生成随机文件名
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() +substring;
//判断文件路径是否存在
        File dir=new File(docPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        try {
//转存到指定位置
            file.transferTo(new File(docPath+fileName));
        } catch (IOException e) {
            throw new CustomException("上传失败了");
        }
        return R.success(fileName);
    }
}
